package com.warski.wonderfires.page.led;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;

import com.suke.widget.SwitchButton;
import com.warski.wonderfires.R;
import com.warski.wonderfires.TheApplication;
import com.warski.wonderfires.net.JsonStep;
import com.warski.wonderfires.net.TCPConn;

import static com.warski.wonderfires.TheApplication.mContext;

/**
 * @author
 *  Led颜色选择界面
 */
public class ToningFragment extends Fragment implements View.OnClickListener {

    private TextView red;
    private TextView green;
    private TextView blue;
    private static boolean flag = true;
    private static boolean checked = true;
    private View oldView;
    private Drawable img;
    private SeekBar seekBar;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_led_toning, container, false);

        img = getResources().getDrawable(R.mipmap.pitch_on);
        root.findViewById(R.id.model_btn).setOnClickListener(v -> goToModel());
        seekBar = root.findViewById(R.id.musictimebar);
        SwitchButton ledSwitch = root.findViewById(R.id.led_switch);
        ledSwitch.setOnCheckedChangeListener((view, isChecked) -> {
            checked = isChecked;
            if (isChecked){
                TCPConn.getInstance().sendData(JsonStep.LedOpen.getJsonString());
                String value = red.getText() + "," + green.getText() + "," + blue.getText() + "," + seekBar.getProgress();
                TCPConn.getInstance().sendData(String.format(JsonStep.LedColorFormatSet.getJsonString(),value));
            }else {
                TCPConn.getInstance().sendData(JsonStep.LedClose.getJsonString());
            }
        });
        // 初始化部分视图
        init(root);
        // 初始化之后再将此设为 true，防止一进入页面就再发送数据
        ok = true;
        // 接收颜色改变返回值广播
        IntentFilter filter = new IntentFilter();
        filter.addAction("color");
        getContext().registerReceiver(colorReceiver, filter);
        return root;
    }

    private BroadcastReceiver colorReceiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if ("color".equals(action)){
                int r = intent.getIntExtra("red",255);
                int g = intent.getIntExtra("green",0);
                int b = intent.getIntExtra("blue",0);
                setColor(r,g,b);
                if (flag) oldView.setBackgroundColor(Color.rgb(r, g, b));
            }
        }
    };

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void init(View root){
        red = root.findViewById(R.id.red_value);
        green = root.findViewById(R.id.green_value);
        blue = root.findViewById(R.id.blue_value);
        // 初始化设置值及颜色
        setColor(255,0,0);
        int height = (TheApplication.width - 166) / 9;

        Button common1 = root.findViewById(R.id.common1);
        Button common2 = root.findViewById(R.id.common2);
        Button common3 = root.findViewById(R.id.common3);
        Button common4 = root.findViewById(R.id.common4);
        Button common5 = root.findViewById(R.id.common5);
        Button common6 = root.findViewById(R.id.common6);
        Button yellowColor = root.findViewById(R.id.yellow_color);
        Button whiteColor = root.findViewById(R.id.white_color);
        Button cyanColor = root.findViewById(R.id.cyan_color);
        Button redColor = root.findViewById(R.id.red_color);
        Button greenColor = root.findViewById(R.id.green_color);
        Button blueColor = root.findViewById(R.id.blue_color);

        oldView = common4;
        oldView.setForeground(img);
        // 设置高度
        common1.getLayoutParams().height = height;
        common2.getLayoutParams().height = height;
        common3.getLayoutParams().height = height;
        common4.getLayoutParams().height = height;
        common5.getLayoutParams().height = height;
        common6.getLayoutParams().height = height;
        yellowColor.getLayoutParams().height = height;
        whiteColor.getLayoutParams().height = height;
        cyanColor.getLayoutParams().height = height;
        redColor.getLayoutParams().height = height;
        greenColor.getLayoutParams().height = height;
        blueColor.getLayoutParams().height = height;
        // 设置监听
        common1.setOnClickListener(this);
        common2.setOnClickListener(this);
        common3.setOnClickListener(this);
        common4.setOnClickListener(this);
        common5.setOnClickListener(this);
        common6.setOnClickListener(this);
        yellowColor.setOnClickListener(this);
        whiteColor.setOnClickListener(this);
        cyanColor.setOnClickListener(this);
        redColor.setOnClickListener(this);
        greenColor.setOnClickListener(this);
        blueColor.setOnClickListener(this);
    }

    private void setColor(int r, int g, int b){
        // 值设置
        red.setText(String.valueOf(r));
        green.setText(String.valueOf(g));
        blue.setText(String.valueOf(b));
        // 背景设置
        red.setBackgroundColor(Color.rgb(r,0,0));
        green.setBackgroundColor(Color.rgb(0,g,0));
        blue.setBackgroundColor(Color.rgb(0,0,b));

        if (checked && ok){
            String value = r + "," + g + "," + b + "," + seekBar.getProgress();
            ok = false;
            TCPConn.getInstance().sendData(String.format(JsonStep.LedColorFormatSet.getJsonString(),value));
            mHandler.postDelayed(mRunnable,300);
        }
    }
    private boolean ok = false;
    private Handler mHandler = new Handler();
    private Runnable mRunnable = () -> ok = true;

    @Override
    public void onDestroy() {
        if (mRunnable != null) {
            mHandler.removeCallbacks(mRunnable);
            mRunnable = null;
        }
        if (mHandler != null) mHandler = null;
        if (colorReceiver != null) mContext.unregisterReceiver(colorReceiver);
        super.onDestroy();
    }

    private void goToModel(){
        Intent intent = new Intent(getActivity(),ModleActivity.class);
        startActivityForResult(intent,233);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onClick(View v) {

        v.setForeground(img);
        ColorDrawable buttonColor = (ColorDrawable) v.getBackground();
        int color = buttonColor.getColor();
        int r = (color & 0xff0000) >> 16;
        int g = (color & 0x00ff00) >> 8;
        int b = (color & 0x0000ff);
        setColor(r,g,b);
        // 去掉上一个的前景图片
        oldView.setForeground(null);
        oldView = v;

        switch (oldView.getId()){
            case R.id.common1:
            case R.id.common2:
            case R.id.common3:
            case R.id.common4:
            case R.id.common5:
            case R.id.common6:
                flag = true;
                break;
            default:
                flag = false;
                break;
        }
    }
}
